//
//  Dictionary+Extension.swift
//  YangFoundation
//
//  Created by yuyang on 2021/12/21.
//

import UIKit

public extension Dictionary {
    /// 字典转 json 字符串
    var jsonStr: String {
        guard JSONSerialization.isValidJSONObject(self) else {
            return ""
        }
        let jsonData = try? JSONSerialization.data(withJSONObject: self)
        if let jsonData = jsonData {
            let str = String.init(data: jsonData, encoding: .utf8)
            return str ?? ""
        }
        return ""
    }

    /// 字典拼接
    func appendDictionary(dict: Dictionary?) -> Dictionary {
        guard dict != nil else {
            return self
        }
        var tmp: Dictionary = [:]
        for (key, value) in self {
            tmp[key] = value
        }
        for (key, value) in dict! {
            tmp[key] = value
        }
        return tmp
    }
}
